package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.domain.Employee;
import com.itheima.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import sun.security.provider.MD5;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){
        // 1.将页面提交的密码password进行md5加密处理, 得到加密后的字符串
        String password = employee.getPassword();
        password=DigestUtils.md5DigestAsHex(password.getBytes());

        // 2.根据页面提交的用户名username查询数据库中员工数据信息
        String username = employee.getUsername();
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<Employee>();
        lqw.eq(Employee::getUsername,username);
        Employee emp = employeeService.getOne(lqw);


        // 3.如果没有查询到, 则返回登录失败结果
        if(emp==null){
            return R.error("用户不存在");
        }
        // 4.密码比对，如果不一致, 则返回登录失败结果
        if(!emp.getPassword().equals(password)){
            return R.error("密码错误");
        }
        // 5.查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if(emp.getStatus()==0){
            return R.error("账号已被禁用");
        }

        // 6.登录成功，将员工id存入Session, 并返回登录成功结果
        HttpSession session = request.getSession();
        session.setAttribute("employee",emp.getId());
        return R.success(emp);
    }

    @PostMapping("/logout")
    public R<String> loginOut(HttpServletRequest request){
        //清除用户id;
        HttpSession session = request.getSession();
        session.removeAttribute("employee");
        return R.success("退出成功");
    }

    @PostMapping
    public R<String> loginAdd(HttpServletRequest request, @RequestBody Employee employee){
        //判断员工是否存在
        LambdaQueryWrapper<Employee> lwq =new LambdaQueryWrapper<Employee>();
        lwq.eq(Employee::getUsername,employee.getUsername());
        Employee one = employeeService.getOne(lwq);

        if(one!=null){
            return R.error("添加失败,用户已存在");
        }
        /*employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());*/
        HttpSession session = request.getSession();
        Long userId = (Long) session.getAttribute("employee");
        /*employee.setCreateUser(userId);
        employee.setUpdateUser(userId);*/
        //用户密码,设置初始密码123456
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(password);

        //添加到数据库
        employeeService.save(employee);
        return R.success("添加成功");

    }
    //分页查询
    @GetMapping("/page")
    public R selectByPage(Integer page,Integer pageSize,String name){
        IPage<Employee> pages = new Page<Employee>(page,pageSize);
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<Employee>();
        //判断关键字是否为null
        if(name!=null){
            lqw.like(Employee::getName,name);
        }

        IPage<Employee> iPage = employeeService.page(pages, lqw);

        return R.success(iPage);

    }

    @PutMapping()
    public R<String> update(HttpServletRequest request,@RequestBody Employee employee){
        if(employee.getId()==1){
            return R.success("该用户不能被禁用");
        }

        //判断修改用户是否存在
        Employee emp= employeeService.getById(employee);
        if(emp==null){
            return R.error("该用户不存在!!");
        }

        //获取用户id
        HttpSession session = request.getSession();
        Long Id = (Long) session.getAttribute("employee");
        long userId = Id.longValue();

        //修改时间
        /*employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(userId);*/
        //employee.setStatus(employee.getStatus());

        //判断是管理员还是修改自身
        if(employee.getId().longValue()==userId||userId==1L){
            //修改到数据库
            employeeService.updateById(employee);
            return R.success("修改状态成功！！");
        }
        return R.error("权限不足!!!");



    }

    //回显功能
    @GetMapping("/{id}")
    public R<Employee> selectById(@PathVariable Long id){
        //从数据库查询用户是否存在
        Employee employee = employeeService.getById(id);
        if(employee==null){
            return R.error("参数异常!");
        }
        return R.success(employee);
    }



}
